<template>
  <div class="register-page">
    <div class="register-container">
      <!-- 头部 -->
      <div class="register-header">
        <van-nav-bar
          title="人脸注册"
          left-text="返回"
          left-arrow
          @click-left="goToLogin"
        />
      </div>

      <!-- 注册内容 -->
      <div class="register-content">
        <div class="logo-section">
          <van-icon name="user-circle-o" size="80" color="#409eff" />
          <h2>创建账户</h2>
          <p>加入AI智能学习助手，开启智能学习之旅</p>
        </div>

        <!-- 基本信息表单 -->
        <van-form @submit="onSubmit" v-if="currentStep === 1">
          <van-cell-group inset>
            <van-field
              v-model="userForm.username"
              name="username"
              label="用户名"
              placeholder="请输入用户名"
              :rules="[{ required: true, message: '请输入用户名' }]"
            />
            <van-field
              v-model="userForm.phone"
              name="phone"
              label="手机号"
              placeholder="请输入手机号"
              :rules="[{ required: true, message: '请输入手机号' }]"
            />
            <van-field
              v-model="userForm.email"
              name="email"
              label="邮箱"
              placeholder="请输入邮箱地址"
              :rules="[{ required: true, message: '请输入邮箱' }]"
            />
          </van-cell-group>

          <div class="form-actions">
            <van-button round block type="primary" native-type="submit">
              下一步
            </van-button>
          </div>
        </van-form>

        <!-- 人脸采集 -->
        <div v-if="currentStep === 2" class="face-capture">
          <h3>人脸信息采集</h3>
          
          <!-- 采集方式选择 -->
          <div class="capture-methods">
            <div 
              class="method-card" 
              :class="{ active: captureMethod === 'camera' }" 
              @click="captureMethod = 'camera'"
            >
              <van-icon name="video-o" size="40" />
              <p>摄像头拍照</p>
            </div>
            
            <div 
              class="method-card" 
              :class="{ active: captureMethod === 'upload' }" 
              @click="captureMethod = 'upload'"
            >
              <van-icon name="photo-o" size="40" />
              <p>上传照片</p>
            </div>
          </div>

          <!-- 摄像头拍照 -->
          <div v-if="captureMethod === 'camera'" class="camera-area">
            <div v-if="!cameraActive && !capturedImage" class="camera-start">
              <div class="camera-placeholder">
                <van-icon name="video-o" size="80" color="#c0c4cc" />
                <p>点击开启摄像头</p>
              </div>
              <van-button
                type="primary"
                size="large"
                @click="startCamera"
                :loading="cameraLoading"
              >
                开启摄像头
              </van-button>
            </div>

            <div v-else-if="cameraActive" class="camera-preview">
              <div class="video-container" id="video-container">
                <div class="face-guide">
                  <div class="face-outline"></div>
                  <p>请将人脸对准中央</p>
                </div>
              </div>
              <div class="camera-controls">
                <van-button type="success" @click="capturePhoto">拍照</van-button>
                <van-button @click="stopCamera">关闭</van-button>
              </div>
            </div>

            <div v-else-if="capturedImage" class="photo-result">
              <div class="photo-preview">
                <img :src="capturedImage" alt="拍摄照片" />
              </div>
              <div class="photo-actions">
                <van-button type="primary" @click="completeRegister" :loading="registerLoading">
                  完成注册
                </van-button>
                <van-button @click="retakePhoto">重新拍照</van-button>
              </div>
            </div>
          </div>

          <!-- 上传照片 -->
          <div v-if="captureMethod === 'upload'" class="upload-area">
            <van-uploader
              v-model="fileList"
              :after-read="afterRead"
              :max-count="1"
              accept="image/*"
            >
              <van-button icon="plus" type="primary">选择图片</van-button>
            </van-uploader>
            
            <div v-if="uploadedImage" class="upload-actions">
              <van-button type="primary" @click="completeRegister" :loading="registerLoading">
                完成注册
              </van-button>
            </div>
          </div>

          <div class="step-actions">
            <van-button @click="prevStep">上一步</van-button>
          </div>
        </div>

        <!-- 注册成功 -->
        <div v-if="currentStep === 3" class="register-success">
          <van-icon name="success" size="80" color="#67c23a" />
          <h3>注册成功！</h3>
          <p>您的账户已创建完成，现在可以使用人脸识别登录了</p>
          <van-button type="primary" @click="goToLogin">立即登录</van-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { showToast } from 'vant'
import { registerFace } from '@/api/face'

const router = useRouter()

// 当前步骤
const currentStep = ref(1)

// 用户表单数据
const userForm = reactive({
  username: '',
  phone: '',
  email: ''
})

// 人脸采集相关
const captureMethod = ref('camera')
const cameraActive = ref(false)
const cameraLoading = ref(false)
const capturedImage = ref('')
const uploadedImage = ref('')
const registerLoading = ref(false)
const fileList = ref([])

// 表单提交
const onSubmit = (values) => {
  if (!values.username || !values.phone || !values.email) {
    showToast('请填写完整信息')
    return
  }
  
  Object.assign(userForm, values)
  currentStep.value = 2
}

// 下一步
const nextStep = () => {
  currentStep.value++
}

// 上一步
const prevStep = () => {
  currentStep.value--
}

// 开启摄像头（简化版本）
const startCamera = async () => {
  cameraLoading.value = true
  try {
    const stream = await navigator.mediaDevices.getUserMedia({
      video: { facingMode: 'user' }
    })
    
    cameraActive.value = true
    
    // 简化的视频处理
    setTimeout(() => {
      const container = document.getElementById('video-container')
      if (container) {
        const video = document.createElement('video')
        video.srcObject = stream
        video.autoplay = true
        video.muted = true
        video.style.width = '100%'
        video.style.height = '100%'
        video.style.objectFit = 'cover'
        container.appendChild(video)
        
        window.currentStream = stream
        window.currentVideo = video
      }
    }, 100)
    
    showToast('摄像头已开启')
  } catch (error) {
    showToast('摄像头开启失败')
  } finally {
    cameraLoading.value = false
  }
}

// 停止摄像头
const stopCamera = () => {
  if (window.currentStream) {
    window.currentStream.getTracks().forEach(track => track.stop())
  }
  cameraActive.value = false
}

// 拍照
const capturePhoto = () => {
  const video = window.currentVideo
  if (!video) return
  
  const canvas = document.createElement('canvas')
  canvas.width = video.videoWidth || 640
  canvas.height = video.videoHeight || 480
  
  const ctx = canvas.getContext('2d')
  ctx.drawImage(video, 0, 0)
  
  capturedImage.value = canvas.toDataURL('image/jpeg', 0.8)
  stopCamera()
  showToast('拍照成功')
}

// 重新拍照
const retakePhoto = () => {
  capturedImage.value = ''
  startCamera()
}

// 文件上传
const afterRead = (file) => {
  uploadedImage.value = file.content
  showToast('图片上传成功')
}

// 完成注册
const completeRegister = async () => {
  const imageData = capturedImage.value || uploadedImage.value
  if (!imageData) {
    showToast('请先采集人脸信息')
    return
  }

  registerLoading.value = true
  try {
    const response = await registerFace({
      username: userForm.username,
      phone: userForm.phone,
      email: userForm.email,
      imageData
    })

    if (response.success || response.code === 200) {
      currentStep.value = 3
      showToast('注册成功！')
    } else {
      showToast(response.message || '注册失败')
    }
  } catch (error) {
    showToast('注册失败，请重试')
  } finally {
    registerLoading.value = false
  }
}

// 返回登录
const goToLogin = () => {
  router.push('/login')
}
</script>

<style scoped>
.register-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.register-container {
  min-height: 100vh;
  background: white;
  margin: 0 auto;
  max-width: 500px;
}

.register-header {
  background: white;
}

.register-content {
  padding: 20px;
}

.logo-section {
  text-align: center;
  margin-bottom: 40px;
}

.logo-section h2 {
  margin: 16px 0 8px 0;
  color: #323233;
}

.logo-section p {
  color: #969799;
  margin: 0;
}

.form-actions {
  margin-top: 24px;
}

.face-capture h3 {
  text-align: center;
  margin-bottom: 24px;
}

.capture-methods {
  display: flex;
  gap: 16px;
  margin-bottom: 24px;
}

.method-card {
  flex: 1;
  text-align: center;
  padding: 20px;
  border: 2px solid #ebedf0;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.3s;
}

.method-card.active {
  border-color: #1989fa;
  background: #f0f9ff;
}

.camera-area, .upload-area {
  text-align: center;
}

.camera-placeholder {
  padding: 40px;
  border: 2px dashed #ebedf0;
  border-radius: 12px;
  margin-bottom: 16px;
}

.video-container {
  width: 100%;
  height: 300px;
  background: #000;
  border-radius: 12px;
  position: relative;
  margin-bottom: 16px;
}

.face-guide {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
}

.face-outline {
  width: 150px;
  height: 180px;
  border: 3px solid #1989fa;
  border-radius: 50%;
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.7; }
}

.face-guide p {
  color: white;
  margin-top: 16px;
}

.camera-controls, .photo-actions, .upload-actions {
  display: flex;
  gap: 12px;
  justify-content: center;
  margin-top: 16px;
}

.photo-preview img {
  max-width: 100%;
  max-height: 300px;
  border-radius: 12px;
}

.step-actions {
  margin-top: 24px;
  text-align: center;
}

.register-success {
  text-align: center;
  padding: 40px 20px;
}

.register-success h3 {
  margin: 16px 0;
  color: #323233;
}

.register-success p {
  color: #969799;
  margin-bottom: 24px;
}
</style>
